/************************************************************************
                        Triangulizer.cpp - Copyright Claudio Botta

This library is free software; you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or 
(at your option) any later version.
This library is distributed in the hope that it will be useful, but 
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public License 
along with this library; if not, write to the 
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, 
Boston, MA 02110, USA

This file was generated on Sat Mar 15 2008 at 10:58:11
The original location of this file is geomagick/Triangulizer.cpp
**************************************************************************/

#include "Triangulizer.h"
using namespace geomagick;
Triangles* Triangulizer::process(Polygons* inPolygons)
{
	Triangles* output = new Triangles();
	vector<Vector3d> VertexCoordinates = *(inPolygons->getVertexCoordinates());
	vector<Vector3d> Normals 	  =  *(inPolygons->getNormals());
	vector<Vector2d> TextureCoordinates = *(inPolygons->getTextureCoordinates());
	vector<Polygon> PolygonList  = *(inPolygons->getPolygonList());

	//The actual triangulization
	foreach(Polygon currentPolygon, PolygonList)
	{

		vector<int> v = currentPolygon.Vertices;
		vector<int> t = currentPolygon.TextureCoordinates;
		vector<int> n = currentPolygon.Normals;
		vector<int>::iterator vi = v.begin();
		vector<int>::iterator ti = t.begin();
		vector<int>::iterator ni = n.begin();
		
		
		int v1 = *vi;
		int v2;
		vi++;
		int v3 = *vi;
		vi ++;
		int n1 = *ni;
		ni++;
		int n2 ;
		int n3 = *ni;
		ni++;
		int t1 = *ti;
		ti++;	
		int t2;
		int t3 = *ti;
		ti++;
		while(vi < v.end())
		{
			v2 = v3;
			n2 = n3;
			t2 = t3;
			
			v3 = *vi;
			vi++;
			t3 = *ti;
			ti++;
			n3 = *ni;
			ni++;
			// Append one triangle
			Triangle newTriangle = *(new Triangle());
			newTriangle.Vertices.push_back(v1);
			newTriangle.Vertices.push_back(v2);
			newTriangle.Vertices.push_back(v3);
			
			newTriangle.Normals.push_back(n1);
			newTriangle.Normals.push_back(n2);
			newTriangle.Normals.push_back(n3);

			newTriangle.TextureCoordinates.push_back(t1);
			newTriangle.TextureCoordinates.push_back(t2);
			newTriangle.TextureCoordinates.push_back(t3);
			output->addTriangle(newTriangle);
		}
		
	}


	// Copy all the other attributes
	foreach(Vector3d VertexCoordinate, VertexCoordinates)
	{
		output->addVertexCoordinates(VertexCoordinate);
	}	
	
	foreach(Vector3d Normal, Normals)
	{
		output->addNormal(Normal);
	}
	
	foreach(Vector2d TextureCoordinate, TextureCoordinates)
	{
		output->addTextureCoordinates(TextureCoordinate);
	}

	return output;
}
